const app = getApp()
import urls from '../../utils/urls.js'

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		messageList: [], //消息记录，我的和接收的
		value: '', //输入的信息
		scrollTop: 10000000,
		increase: false, //图片添加区域隐藏
		aniStyle: true, //动画效果
		message: "",
		toUid: '', //聊天对象用户ID
		socketInstance: null, //连接对象
		connectStatus: false, //连接状态
		webUrl: '',
		times:[],
		page:1,
		totalSize: 0,
		isFromTeacher: 0,
		title: '咨询',
		avatar: '',
		nickName: ''
	},
	sendMsgs(msg) {
		let that = this;
		msg = JSON.stringify(msg)
		// wx.onSocketOpen(() => {
			wx.sendSocketMessage({
				data: msg,
				success: function(res) {
					console.log('消息发送成功', res);
					that.setData({
						value: '',
						scrollTop: 1000000
					});
					that.scrollToBottom();
				},
				fail: function(res) {
					console.log('消息发送出错', res)
				}
			})
		// });
		
	},
	//滚动动最底部
	scrollToBottom(){
		this.setData({
			scrollTop: 1000000
		});
	},
	//发送消息
	sendMsg: function(res) {
		if(!this.data.value) {
			return false;
		}


		console.log('发送信息', res)
		var userInfo = loginFn();

		let loginInfo = {
			"cmd": "sendTo",
			"loginUid": userInfo.loginUid,
			"loginTime": userInfo.loginTime,
			"loginKey": userInfo.loginKey,
			"msg": this.data.value,
			"toUid": this.data.toUid,
			// "toUid": userInfo.loginUid,
			"nick": this.data.nickName,
			"avatar": this.data.avatar,
			"isFromTeacher": this.data.isFromTeacher,
			"schoolId": this.data.schoolId,
			"teacherId": this.data.teacherId,
		};
		console.log('发送消息内容', loginInfo)
		this.sendMsgs(loginInfo)

		let messageList = this.data.messageList;
		loginInfo.type = 1;
		messageList.push(loginInfo);
		this.setData({
			messageList: messageList
		})
	},
	sendMessage: function(e) {
		let values = e.detail.value
		this.setData({
			value: values
		})
	},
	// 加号按钮
	increase: function() {
		this.setData({
			increase: true,
			aniStyle: true
		})
	},


	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		console.log('聊天页面接收参数', options);
		let that = this;
		this.setData({
			toUid: options.uid ? options.uid : '',
			webUrl: urls.zhaopeixun,
			title: options.name ? options.name : '咨询',
			toUserAvatar: options.avatar ? options.avatar : '',
			schoolId: options.schoolId ? options.schoolId : 0,
			teacherId: options.teacherId ? options.teacherId : 0,
		});

		if(options.from && options.from == 'admin') {
			this.setData({
				isFromTeacher: 1
			});
		}

		this.initScoket();
		this.getMessageList();
		wx.getUserInfo({
			success: function(res) {
				that.setData({
					avatar: res.userInfo.avatarUrl,
					nickName: res.userInfo.nickName
				});
			}
		});

	},


	//初始化websocket
	initScoket(){
		let that = this;
		wx.connectSocket({
			url: urls.websocketUrl,
			success: function(res) {
				console.log('连接成功', res);
			},
			fail: function(res) {
				console.log('连接出错', res);
			}
		});

		

		wx.onSocketError((res) => {
			this.setData({
				connectStatus: false
			});
			console.log('连接出错', res);
		});

		wx.onSocketClose((res) => {
			this.setData({
				connectStatus: false
			});
			console.log('连接已关闭', res);
			// this.initScoket();
		});

		wx.onSocketMessage((res) => {
			this.getMessage(res);
		});

		wx.onSocketOpen((res) => {
			console.log('websocket已打开！', res);
			
			this.setData({
				connectStatus: true
			});
		})
		
	},

	//连接说明请求用户
	joinWebsocket(){
		console.log('join')
		let userInfo = wx.getStorageSync('userinfo');
		var loginInfo = {
			"cmd": "joinHall",
			"loginUid": userInfo.loginUid,
			"loginTime": userInfo.loginTime,
			"loginKey": userInfo.loginKey,
			"nick": this.data.nickName,
			"avatar": userInfo.avatar
		};

		console.log('发送消息内容', loginInfo)
		setTimeout(() =>{
			this.sendMsgs(loginInfo);
		},1000);
	},

	//接收信息处理
	getMessage(message) {
		var that = this;
		console.log('服务器返回的消息', message);
		let messageList = this.data.messageList;
		let resMsg = JSON.parse(message.data);
		var userInfo = wx.getStorageSync('userinfo');
		var uid = userInfo.loginUid;
		if(resMsg.fromUid == this.data.toUid) {
			resMsg.type = 2;
			messageList.push(resMsg);
			this.setData({

				messageList: messageList
			})
			that.scrollToBottom();
		}
		
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {
		this.joinWebsocket();
	},
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		wx.closeSocket();
	},
	getMessageList(){
		let that = this;
		let page = this.data.page;
		let totalSize = this.data.totalSize;
		let list = this.data.messageList;
		if(page > 1 && list.length >= totalSize) {
			return false;
		}

		app.request({
			url: 'message/list',
			data: {
				user_id: that.data.toUid,
				page: page
			},
			sCallback:(res) => {
				console.log(res);
				if(res.code == 1) {
					let resData = res.data.list;
					resData.reverse();
					let messageList = resData.concat(list);
					page ++;
					that.setData({
						messageList: messageList,
						page: page,
						totalSize: res.data.total_size,
						toUserAvatar: res.data.user.fromAvatar,
						title: res.data.user.fromNick
					});
					if(page == 2) {
						that.scrollToBottom();
					}
				}
			}
		})

	},
})
